package com.jcnet.bizaia.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.weibo.TencentWeibo;
import cn.sharesdk.tencent.weibo.TencentWeibo.ShareParams;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jcnet.bizaia.App;
import com.jcnet.bizaia.MyJCDownloadActivity;
import com.jcnet.bizaia.R;
import com.jcnet.bizaia.VodDetailActivity;
import com.jcnet.bizaia.VoiceTalkActivity;
import com.jcnet.bizaia.adapter.MainVoiceDeatalAdapter;
import com.jcnet.bizaia.bean.SPUserBean;
import com.jcnet.bizaia.bean.StateBean;
import com.jcnet.bizaia.bean.VoiceDetailBean;
import com.jcnet.bizaia.tools.FileUtils;
import com.jcnet.bizaia.tools.JCTools;
import com.jcnet.bizaia.tools.MusicTools;
import com.jcnet.bizaia.tools.Toolkit;
import com.jcnet.bizaia.view.HeadViewPageView;
import com.jcnet.bizaia.view.ProgressHUD;
import com.jcnet.bizaia.xstream.ACache;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mozillaonline.downloadprovider.DownloadProviderActivity;
import com.mozillaonline.providers.DownloadManager;
import com.mozillaonline.providers.DownloadManager.Request;
import com.mozillaonline.providers.downloads.DownloadService;
import com.mozillaonline.providers.downloads.ui.DownloadList;
import com.tjerkw.slideexpandable.library.ActionSlideExpandableListView;
import com.tjerkw.slideexpandable.library.ActionSlideExpandableListView.OnActionClickListener;


/**
 * @author chenguandong
 * @category  主页下 音乐分类下的详细
 *
 */
@SuppressLint("ValidFragment")
public class VoiceDetailFragment extends Fragment implements OnItemClickListener {


	private List<VoiceDetailBean> mainInfoBeans;

	private List<VoiceDetailBean>tempInfoBeans;

	private ActionSlideExpandableListView listView;

	private View bottomView;  //底部加载更多按钮

	private View headViewPageView;

	private View emptyView;     //数据为空

	private View noNetWorkView;  //没有网络\


	private View firstLodingView;  //没有网络\

	private MainVoiceDeatalAdapter infoAdapter;

	private int nowPageSize = 1;

	private int category =2;

	private ACache aCache;

	private String HTTP_REQUEST =  App.HTTP_PATH+"sud_showSoundList.action?";

	private RequestParams params;

	private int allPapeSize;

	private boolean mLastItemVisible;

	private MusicMediaControllerFragment musicControllFragment;


	DownloadManager mDownloadManager;

	private static final String TAG = DownloadProviderActivity.class.getName();

	private BroadcastReceiver mReceiver;
	
	private ProgressHUD progressHUD;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		mDownloadManager = new DownloadManager(getActivity().getContentResolver(),
				getActivity().getPackageName());

		startDownloadService();

		mReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				showDownloadList();
			}
		};

		getActivity().registerReceiver(mReceiver, new IntentFilter(
				DownloadManager.ACTION_NOTIFICATION_CLICKED));


	aCache = ACache.get(getActivity());

	params = new RequestParams();

	View view = View.inflate(getActivity(), R.layout.voice_detail,null);

	bottomView = View.inflate(getActivity(), R.layout.comm_foot_view, null);

	firstLodingView = View.inflate(getActivity(), R.layout.init_locad_view, null);

	headViewPageView = new HeadViewPageView(getActivity(), category);

	listView = (ActionSlideExpandableListView)view.findViewById(R.id.commListViewBase);

	emptyView = View.inflate(getActivity(), R.layout.list_empty_no_data, null);

	noNetWorkView = View.inflate(getActivity(), R.layout.list_no_network, null);

	initListView();
	System.out.println("onCreateView__________________");


	return view;
}

	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		getActivity().unregisterReceiver(mReceiver);
	}
	
	
private void startDownloadService() {
	Intent intent = new Intent();
	intent.setClass(getActivity(), DownloadService.class);
	getActivity().startService(intent);
}


private void showDownloadList() {
	Intent intent = new Intent();
	//intent.setClass(context, DownloadList.class);
	//intent.setClass(context, JCDownloadList.class);
	intent.setClass(getActivity(), MyJCDownloadActivity.class);
	startActivity(intent);
}

public static VoiceDetailFragment newInstance(int category) {
	VoiceDetailFragment fragment = new VoiceDetailFragment();
	fragment.category = category;
	return fragment;
}


public VoiceDetailFragment() {
	super();
	// TODO Auto-generated constructor stub
}





public VoiceDetailFragment(int category) {
	super();
	this.category = category;
}



@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
	// TODO Auto-generated method stub
	if(isVisibleToUser){
		System.out.println("onCreateView__________________");
	}
	super.setUserVisibleHint(isVisibleToUser);
}

private void initListView() {
	// TODO Auto-generated method stub
	musicControllFragment = (MusicMediaControllerFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.musicControlFragment);
	mainInfoBeans = new ArrayList<VoiceDetailBean>();

	tempInfoBeans = new ArrayList<VoiceDetailBean>();


	infoAdapter = new MainVoiceDeatalAdapter(getActivity(), mainInfoBeans);


	listView.setOnItemClickListener(this);

	listView.setItemActionListener(new OnActionClickListener() {

		@Override
		public void onClick(View listView, View buttonview, int position) {
			// TODO Auto-generated method stub
			if(buttonview.getId()==R.id.buttonPlay) {
				if(!mainInfoBeans.isEmpty()){
					MusicTools.musicSetPlayList(getActivity(), mainInfoBeans, position);
					musicControllFragment.play();
				}
				
			} 
			if(buttonview.getId()==R.id.buttonTalk){

				Intent intent = new Intent(getActivity(),VoiceTalkActivity.class);
				VoiceDetailBean voiceDetailBean = mainInfoBeans.get(position);
				intent.putExtra("voiceDetailBean", voiceDetailBean);
				startActivity(intent);
			}
			if(buttonview.getId()==R.id.buttonDownload){


				Uri srcUri = Uri.parse(App.HTTP_PATH+mainInfoBeans.get(position).getVideourl());
				DownloadManager.Request request = new Request(srcUri);
				/**
				 * context
				 * file path
				 * file name
				 */
				request.setDestinationInExternalFilesDir(getActivity(),App.DOWNLOAD_VOICE_PATH, "/");
				request.setDescription("dwonloading...");
				mDownloadManager.enqueue(request);
				
				//showDownloadList();

			}
			
			if(buttonview.getId()==R.id.buttonStart){    //收藏
					
				sendStartLoveIt(position);
				
			}
			if(buttonview.getId()==R.id.buttonShare){
				Toast.makeText(getActivity(), "share", 0).show();
				ShareParams sp = new ShareParams();
				sp.setText("http://www.baidu.com");
				Platform weibo = ShareSDK.getPlatform(getActivity(), TencentWeibo.NAME);
				weibo.setPlatformActionListener(new PlatformActionListener() {
					
					@Override
					public void onError(Platform arg0, int arg1, Throwable arg2) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onCancel(Platform arg0, int arg1) {
						// TODO Auto-generated method stub
						
					}
				});
				weibo.share(sp);
			
			}


		}

		
	}, 
	R.id.buttonPlay,
	R.id.buttonTalk,
	R.id.buttonStart,
	R.id.buttonDownload,
	R.id.buttonShare
			);



	listView.setAdapter(infoAdapter);
	listView.setOnItemClickListener(this);
	listView.setEmptyView(firstLodingView);
	//simpleListView.addHeaderView(headViewPageView);
	listView.addFooterView(bottomView);
	sendHttp(nowPageSize);


	listView.setOnScrollListener(new OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE  && mLastItemVisible) {


				if(nowPageSize==allPapeSize){
					bottomView.setVisibility(View.GONE);   //到达底部没有更多数据
					Toast.makeText(getActivity(), getString(R.string.noData), 0).show();
				}else{
					bottomView.setVisibility(View.VISIBLE);  //到达底部还有更多数据
					nowPageSize = nowPageSize+1;
					sendHttp(nowPageSize);
				}

			}

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			mLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1);

		}
	});




}





public void sendHttp(int page){


	/**
		 参数名称
				参数类型
				说明
				languageNum
				int
				语言种类：1：中文2：英文3：日文
				datelineNum
				date
				时间日期检索（搜索全部时赋值null/-1等均可）
				title
				string
				音频标题
				cidNum
				int
				分类id检索（默认全部时赋值-1）
				pageNum
				int
				当前第几页（默认第一页）
				pageSizeNum
				int
				当前分页显示条数（默认20条）

	 */
	params.put("languageNum", App.localeCode+"");
	params.put("datelineNum", "-1");     	//音频时间 
	params.put("title", "");     	//音频标题
	params.put("cidNum", "");     	//音频ID
	params.put("pageNum", page+"");

	//params.put("pageSizeNum",20);   //默认不传20 


	if(Toolkit.isAvaliable(getActivity())){

		new AsyncHttpClient().post(HTTP_REQUEST,params ,new AsyncHttpResponseHandler(){

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();

			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub\

				super.onSuccess(arg0, arg1, arg2);

				setListData(new String(arg2));


			}


			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				super.onFinish();
				bottomView.setVisibility(View.GONE);
			}

			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), getString(R.string.serverError), 0).show();
				super.onFailure(arg0, arg1, arg2, arg3);
			}
		});
	}else{

		listView.setEmptyView(noNetWorkView);


		firstLodingView.setVisibility(View.GONE);

		String requestString = aCache.getAsJSONObject(HTTP_REQUEST+params).toString();

		if(requestString!=null){

			setListData(requestString);
		}


		Toast.makeText(getActivity(), getString(R.string.noNetWork), 1).show();

	}
}


private void setListData(String arg2){



	String requestString = arg2;

	AllVoidRequestData requestBeanRequest = new AllVoidRequestData();

	//System.out.println("byte:"+new String(arg2));

	if(requestString!=null){

		aCache.put(HTTP_REQUEST+params, requestString,App.CACHE_TIME_DAY);

		requestBeanRequest = new Gson().fromJson(requestString, new TypeToken<AllVoidRequestData>(){}.getType());


		allPapeSize = requestBeanRequest.getPagsum();

		if(requestBeanRequest.getState()==200){

			firstLodingView.setVisibility(View.GONE);

			tempInfoBeans = null;

			tempInfoBeans = requestBeanRequest.getObjlistJson();

			if(!tempInfoBeans.isEmpty()||tempInfoBeans!=null){

				if(tempInfoBeans.isEmpty()||mainInfoBeans.size()<20){   //当本页的


					bottomView.setVisibility(View.GONE);

				}

				if(!tempInfoBeans.isEmpty()){

					mainInfoBeans.addAll(tempInfoBeans);

					infoAdapter.count = mainInfoBeans.size();

					infoAdapter.notifyDataSetChanged();
				}
			}


			//如果得到的内容总数为空的话显示没有数据的页面,同时隐藏foot界面
			if(mainInfoBeans.isEmpty()){
				listView.setEmptyView(emptyView);
				bottomView.setVisibility(View.GONE);
			}


		}

	}

}

private void sendStartLoveIt( int postion) {
	// TODO Auto-generated method stub
	if(Toolkit.isAvaliable(getActivity())){
		RequestParams params = new RequestParams();
		params.put("useridNum", JCTools.getUserID(getActivity())+"");  //用户ID
		params.put("didNum", mainInfoBeans.get(postion).getSid()+"");   //评论信息ID
		params.put("ftypeNum", "2");  //0 1 2
		
		new AsyncHttpClient().post(App.HTTP_PATH+"favo_addFavourites.action?", params, new AsyncHttpResponseHandler(){
			
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				progressHUD = ProgressHUD.show(getActivity(), getString(R.string.commiting), true	, false, null);
				super.onStart();
			}
			
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				super.onSuccess(arg0, arg1, arg2);
				
				StateBean stateBean = new Gson().fromJson(new String(arg2), new TypeToken<StateBean>(){}.getType());
			
				if(stateBean.getState()==200){
					Toast.makeText(getActivity(), "评论成功", 0).show();
					
					
				}else{
					Toast.makeText(getActivity(), stateBean.getMessage()+"", 0).show();
				}
			}
			
			
			@Override
			public void onFinish() {
				// TODO Auto-generated method stub
				super.onFinish();
				if(progressHUD.isShowing()){
					progressHUD.cancel();
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
				super.onFailure(arg0, arg1, arg2, arg3);
				if(progressHUD.isShowing()){
					progressHUD.cancel();
				}
				Toast.makeText(getActivity(), getText(R.string.serverError), 0).show();
			}
		});
		
		
	}else{
		Toast.makeText(getActivity(), R.string.noNetWork, 0).show();
	}
	
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
	// TODO Auto-generated method stub
	/*String source = "http://devimages.apple.com/iphone/samples/bipbop/gear4/prog_index.m3u8";
		//Intent intent = new Intent(getActivity(), VideoViewPlayingActivity.class);
		Intent intent = new Intent(getActivity(), VodDetailActivity.class);


		intent.setData(Uri.parse(source));


		startActivity(intent);	*/

	Toast.makeText(getActivity(), "xx", 0).show();

}


class AllVoidRequestData{
	private  int state;
	private  String message;
	private int pagsum;
	private  List<VoiceDetailBean> objlistJson;
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	public int getPagsum() {
		return pagsum;
	}
	public void setPagsum(int pagsum) {
		this.pagsum = pagsum;
	}
	public List<VoiceDetailBean> getObjlistJson() {
		return objlistJson;
	}
	public void setObjlistJson(List<VoiceDetailBean> objlistJson) {
		this.objlistJson = objlistJson;
	}



}

}
